import React, {useState, useEffect, useRef} from 'react';
import {View, Text, SafeAreaView, Button, Dimensions} from 'react-native';
import MapView, {PROVIDER_GOOGLE} from 'react-native-maps';
import {connect} from 'react-redux';

import {Header, LottieBox} from '@/components';

import GlobalStyles from '@/styles/globalStyles';

const blockedAnimation = require('@/assets/animations/blocked.json');
const END_FRAME = 90;

const Home = ({navigation, dispatch, getDataLoading, globalStore: {count}}) => {
  const [poem, setPoem] = useState('--');
  const ref = useRef(null);

  useEffect(() => {
    ref?.current?.play(0, END_FRAME);
  }, []);

  const onTurnTo = () => {
    navigation.navigate('Setting');
  };

  const onAddCount = () => {
    dispatch({type: 'globalStore/addCount'});
  };

  const getData = () => {
    dispatch({
      type: 'globalStore/getData',
      payload: {
        client: 'browser-sdk/1.2',
        'X-User-Token': 'vl0PGvemYRtYbfx6NkFlFBzMY%2Bi0rYTC',
      },
    })
      .then(res => {
        const result = res;
        // console.log('==p====', result);
        setPoem(result?.data?.content);
      })
      .catch(err => {
        console.log('==err====', err);
      });
  };

  return (
    <SafeAreaView style={GlobalStyles.safeArea}>
      <View>
        <LottieBox source={blockedAnimation} autoPlay={false} loop={true} />
        <MapView
          // onMapLoaded={() => console.log('MAP IS LOADED')}
          provider={PROVIDER_GOOGLE}
          mapType="standard"
          initialRegion={{
            latitude: 41.3995345,
            longitude: 2.1909796,
            latitudeDelta: 0.003,
            longitudeDelta: 0.003,
          }}
          style={{height: 200, width: Dimensions.get('window').width}}
        />

        <Header text={'Home'} />
        <Button title="跳转setting" onPress={onTurnTo} />
        <Button title={`加数（${count}）`} onPress={onAddCount} />
        <Button title="获取诗句" onPress={getData} />
        <Text>{poem}</Text>
        <Button title="Toast" onPress={() => Toast.show('分享成功')} />
      </View>
    </SafeAreaView>
  );
};

export default connect(({globalStore, loading}) => ({
  globalStore,
  getDataLoading: loading.effects['globalStore/getData'],
}))(Home);
